#!/usr/bin/env python
# coding: utf-8

import os
import pyodbc
import sys
import traceback

import itchat

reload(sys)
sys.setdefaultencoding('utf-8')


def cur_file_dir():
    # 获取脚本路径
    path = sys.path[0]
    # 判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)


def loginCallback():
    conn = pyodbc.connect(r'DSN=MYMSSQL;DATABASE=CD20151104105802;UID=bqf2016;PWD=admin888')
    cursor = conn.cursor()
    try:
        cursor.execute(" select wxh from wx_status where wxh = ? ", selfWxh)
        wx_status_one = cursor.fetchone()
        cursor.execute(" SELECT FItemID FROM t_submessage WHERE FParentID = 19 AND FName = ? ", selfWxh)
        t_submessage_one = cursor.fetchone()
        wxid = t_submessage_one[0]
        if wx_status_one == None and t_submessage_one != None:
            jsonObj = itchat.web_init()
            uin = jsonObj['User']['Uin']
            cursor.execute("SELECT FName FROM t_login a, t_VXManage b WHERE a.FItemID = b.FUserID AND b.FItemID = 483");
            t_login_one = cursor.fetchone()
            name = t_login_one[0]
            cursor.execute(" insert into wx_relation (uin,wxid) values (?,?) ", uin, wxid)
            cursor.execute(" insert into wx_status (wxh,status,remark) values (?,?,?) ", selfWxh, 0, name);
            cursor.commit()
    except:
        traceback.print_exc()

    cursor.close()
    conn.close()

    itchat.logout()


def main():
    global selfWxh
    selfWxh = sys.argv[1]
    temp_pwd = cur_file_dir() + '/rukutemp/' + selfWxh
    if os.path.exists(temp_pwd) == False:
        os.makedirs(temp_pwd)

    itchat.auto_login(picDir=temp_pwd + '/qr.png', loginCallback=loginCallback)

    itchat.run()


if __name__ == '__main__':
    main()
